﻿using System.Collections;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEditor.Animations;
using UnityEngine;
using UnityEditor;
public class StateTransform : MonoBehaviour
{
    public AnimatorController controller;
    // Start is called before the first frame update
    void Start()
    {


    }

    // Update is called once per frame
    void Update()
    {

    }

    [Button("process")]
    public void Process()
    {
        Dictionary<string, int> sharedStateID = new Dictionary<string, int>();
        SSMachine machine = ScriptableObject.CreateInstance<SSMachine>();
        machine.states = new List<SSMState>();

        var layer = controller.layers[0];
        var states = layer.stateMachine.states;

        // 分配id
        for (int i = 0; i < states.Length; i++)
        {
            sharedStateID.Add(states[i].state.name, i + 2);
        }

        // any state的转换数据放在最前        
        SSMState anyState = new SSMState(1);
        foreach (var trans in layer.stateMachine.anyStateTransitions)
        {
            SSMTranstion transtion = new SSMTranstion();
            transtion.destinationState = sharedStateID[trans.destinationState.name];
            transtion.conditions = new SSMCondition[trans.conditions.Length];
            for (int i = 0; i < trans.conditions.Length; i++)
            {
                SSMCondition condition = new SSMCondition(trans.conditions[i].parameter, (int)trans.conditions[i].mode, trans.conditions[i].threshold);
                transtion.conditions[i] = condition;
            }
            anyState.transtions.Add(transtion);
        }
        machine.states.Add(anyState);

        foreach (var state in states)
        {
            machine.states.Add(FormatStateData(state.state, sharedStateID));
        }

        AssetDatabase.CreateAsset(machine, "Assets/SkillStateMachine/asd.asset");

    }

    public SSMState FormatStateData(AnimatorState state, Dictionary<string, int> sharedStateID)
    {
        SSMState ssmState = new SSMState(
                sharedStateID[state.name],
                state.tag.Equals(string.Empty) ? 0 : int.Parse(state.tag),
                state.transitions.Length <= 0
            );
        foreach (var trans in state.transitions)
        {
            SSMTranstion transtion = new SSMTranstion();
            transtion.destinationState = sharedStateID[trans.destinationState.name];
            transtion.conditions = new SSMCondition[trans.conditions.Length];
            for (int i = 0; i < trans.conditions.Length; i++)
            {
                SSMCondition condition = new SSMCondition(trans.conditions[i].parameter, (int)trans.conditions[i].mode, trans.conditions[i].threshold);
                transtion.conditions[i] = condition;
            }
            ssmState.transtions.Add(transtion);
        }
        return ssmState;
    }

}
